package models.weixin;

import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 *
 * 用户等级分类划分，方便动态选择用户设置购买最低金额
 * Created by weiwei on 2018-02-22.
 */
@Entity
@Table(name="web_user_classify")
public class WebUserClassify extends BaseModel {


    /**
     * 所属商户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;

    /**
     * 名称
     */
    @Column(name = "name")
    public String name;


    /**
     *最低购买金额
     */
    @Column(name = "min_amount")
    public Float  minAmount;


    /**
     *
     */
    @Column(name = "level")
    public int  level;


    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;


    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public static WebUserClassify findByWebUserClassifyId(long id){
        return WebUserClassify.find(" id = ? and  deleted = ?" , id , DeletedStatus.UN_DELETED).first();
    }


    /**
     * 查询分类下的webUser
     * @param webUserClassifyId
     * @return
     */
    public static List<Map<String , Object>> loadItemList(long webUserClassifyId){

        String sqlSelect = "select b.id , c.id as web_user_id , c.nick_name , d.user_name , d.phone , d.confirm_address from web_user_classify a   " +
                "  left join web_user_classify_items b on a.id = b.web_user_classify_id  " +
                "  left join power_web_users c on b.web_user_id = c.id  " +
                "  left join address d on c.id = d.web_user_id and d.deleted = 0 and d.is_default = 1 where a.id = "+webUserClassifyId+" and b.deleted = 0";

        Query query = WebUserClassify.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> dataList = query.getResultList();
        return dataList ;
    }



}
